﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace maskx.JqGridHelper
{
    public class JqGridSearchFilter
    {
        /// <summary>
        /// 多字段查询时分组类型，主要是AND或者OR
        /// </summary>
        public String groupOp { get; set; }
        /// <summary>
        /// 多字段查询时候，查询条件的集合
        /// </summary>
        public JqGridSearchRule[] rules { get; set; }
        public JqGridSearchFilter[] groups { get; set; }
        public string JsonString
        {
            get;
            private set;
        }

        public static JqGridSearchFilter Load(string json)
        {
            if (string.IsNullOrEmpty(json))
                return null;
            JqGridSearchFilter filter = new JqGridSearchFilter();
            Newtonsoft.Json.JsonSerializer s = new Newtonsoft.Json.JsonSerializer();
            TextReader textReader = new StringReader(json);
            Newtonsoft.Json.JsonTextReader r = new Newtonsoft.Json.JsonTextReader(textReader);
            var JContainer = s.Deserialize(r) as Newtonsoft.Json.Linq.JContainer;
            filter = JqGridSearchFilter.Load(JContainer);
            filter.JsonString = json;
            return filter;
        }
        private static JqGridSearchFilter Load(Newtonsoft.Json.Linq.JToken token)
        {
            JqGridSearchFilter filter = new JqGridSearchFilter();
            filter.groupOp = token.Value<string>("groupOp");
            var rules = token["rules"] as Newtonsoft.Json.Linq.JArray;
            if (rules != null)
            {
                filter.rules = new JqGridSearchRule[rules.Count];
                for (int i = 0; i < rules.Count; i++)
                {
                    filter.rules[i] = new JqGridSearchRule();
                    filter.rules[i].op = rules[i].Value<string>("op");
                    filter.rules[i].field = rules[i].Value<string>("field");
                    filter.rules[i].data = rules[i].Value<string>("data");
                }
            }
            if (token["groups"] != null)
            {
                var groups = token.Value<Newtonsoft.Json.Linq.JContainer>("groups");
                if (groups != null)
                {
                    filter.groups = new JqGridSearchFilter[groups.Count];
                    for (int i = 0; i < groups.Count; i++)
                    {
                        filter.groups[i] = JqGridSearchFilter.Load(groups[i]);
                    }
                }
            }
            return filter;
        }
    }
}
